package com.jinly.ryder.ssh.command;

import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.Session;
import com.jinly.ryder.ssh.command.model.FileInfo;
import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Slf4j
public class FileListCommand {
    private Session sshSession;

    public FileListCommand(Session sshSession) {
        this.sshSession = sshSession;
    }

    public List<FileInfo> exec(String fileDir) {
        ChannelExec channelExec = null;
        BufferedReader input = null;
        List<FileInfo> list = new ArrayList<>();
        String command = "ls --full-time " + fileDir;
        try {

            channelExec = (ChannelExec) sshSession.openChannel("exec");
            channelExec.setCommand(command);
            channelExec.connect();
            input = new BufferedReader(new InputStreamReader(channelExec.getInputStream()));
            String line;

            while ((line = input.readLine()) != null) {
                String[] row = line.split(" +");
                if (row.length > 5) {
                    char type = row[0].charAt(0);
                    String size = row[4];
                    String date = row[5];
                    String time = row[6];
                    String fileName = line.split(" +")[8];
                    FileInfo fileInfo = new FileInfo();
                    fileInfo.setModifyTime(LocalDateTime.parse(date + "T" + time));
                    fileInfo.setFileName(fileName);
                    if (type == 'd') {
                        fileInfo.setFileType(1);
                    } else if (type == '-') {
                        fileInfo.setFileType(2);
                    } else if (type == 'l') {
                        fileInfo.setFileType(3);
                    }
                    fileInfo.setSize(Long.parseLong(size));
                    fileInfo.setFileDir(fileDir);
                    if (fileInfo.getFileType() == 3) {
                        fileInfo.setFileLink(row[10]);
                    }
                    list.add(fileInfo);
                }
            }
        } catch (Exception e) {
            log.error("ssh {} err:{}", command, e.getMessage(), e);
        } finally {
            try {
                if (input != null) input.close();
                if (channelExec != null) channelExec.disconnect();
            } catch (Exception e) {
            }
        }
        return list;
    }
}
